const HttpService = function ($http, $q, $state) {
  "ngInject";

  const service = {};
  const BASE_URL = "/api";

  // 获取认证头
  function getAuthHeaders() {
    // 优先从 ngStorage 聚合键读取
    function getTokenFromNgStorage(storage) {
      try {
        const raw = storage.getItem("ngStorage");
        if (!raw) return null;
        const parsed = JSON.parse(raw);
        return parsed && parsed.authToken ? parsed.authToken : null;
      } catch (e) {
        return null;
      }
    }

    // 兼容不同的存储键位
    function parseMaybeJson(value) {
      if (value == null) return null;
      try {
        return JSON.parse(value);
      } catch (e) {
        return value;
      }
    }

    const candidates = [
      getTokenFromNgStorage(localStorage),
      getTokenFromNgStorage(sessionStorage),
      parseMaybeJson(localStorage.getItem("ngStorage-authToken")),
      parseMaybeJson(sessionStorage.getItem("ngStorage-authToken")),
      localStorage.getItem("authToken"),
      sessionStorage.getItem("authToken"),
    ];

    const token = candidates.find(Boolean);
    return token ? { Authorization: `Bearer ${token}` } : {};
  }

  // 通用请求方法
  function request(method, url, data = null, config = {}) {
    const requestConfig = {
      method,
      url: `${BASE_URL}${url}`,
      headers: {
        "Content-Type": "application/json",
        ...getAuthHeaders(),
        ...config.headers,
      },
      ...config,
    };

    if (data) {
      requestConfig.data = data;
    }

    return $http(requestConfig)
      .then((response) => response.data)
      .catch((error) => {
        const errorData = error.data || { success: false, message: "网络错误" };

        // 如果是401错误，清除本地存储的token并跳转到登录页
        if (error.status === 401) {
          localStorage.removeItem("ngStorage-authToken");
          localStorage.removeItem("ngStorage-currentUser");
          sessionStorage.removeItem("ngStorage-authToken");
          sessionStorage.removeItem("ngStorage-currentUser");
          try {
            localStorage.removeItem("authToken");
            sessionStorage.removeItem("authToken");
          } catch (e) {}

          // 跳转到登录页
          $state.go("login");
        }

        return $q.reject(errorData);
      });
  }

  // GET 请求
  service.get = function (url, config = {}) {
    return request("GET", url, null, config);
  };

  // POST 请求
  service.post = function (url, data, config = {}) {
    return request("POST", url, data, config);
  };

  // PUT 请求
  service.put = function (url, data, config = {}) {
    return request("PUT", url, data, config);
  };

  // DELETE 请求
  service.delete = function (url, config = {}) {
    return request("DELETE", url, null, config);
  };

  // 认证相关API
  service.auth = {
    login: function (credentials) {
      return service.post("/auth/login", credentials);
    },
    logout: function () {
      return service.post("/auth/logout");
    },
    getMe: function () {
      return service.get("/auth/me");
    },
  };

  // 工单相关API
  service.tickets = {
    list: function (params = {}) {
      const queryString = Object.keys(params)
        .filter((key) => params[key] !== undefined && params[key] !== "")
        .map((key) => `${key}=${encodeURIComponent(params[key])}`)
        .join("&");

      const url = `/tickets${queryString ? "?" + queryString : ""}`;
      return service.get(url);
    },

    create: function (ticketData) {
      return service.post("/tickets", ticketData);
    },

    getById: function (id) {
      return service.get(`/tickets/${id}`);
    },

    update: function (id, updateData) {
      return service.put(`/tickets/${id}`, updateData);
    },

    delete: function (id) {
      return service.delete(`/tickets/${id}`);
    },
  };

  // 待办相关API
  service.todos = {
    list: function (params = {}) {
      const queryString = Object.keys(params)
        .filter((key) => params[key] !== undefined && params[key] !== "")
        .map((key) => `${key}=${encodeURIComponent(params[key])}`)
        .join("&");

      const url = `/todos${queryString ? "?" + queryString : ""}`;
      return service.get(url);
    },

    create: function (todoData) {
      return service.post("/todos", todoData);
    },

    update: function (id, updateData) {
      return service.put(`/todos/${id}`, updateData);
    },

    delete: function (id) {
      return service.delete(`/todos/${id}`);
    },
  };

  // 用户相关API
  service.users = {
    list: function (params = {}) {
      const queryString = Object.keys(params)
        .filter((key) => params[key] !== undefined && params[key] !== "")
        .map((key) => `${key}=${encodeURIComponent(params[key])}`)
        .join("&");

      const url = `/users${queryString ? "?" + queryString : ""}`;
      return service.get(url);
    },

    getSupportStaff: function () {
      return service.get("/users/support-staff");
    },

    create: function (userData) {
      return service.post("/users", userData);
    },
  };

  // 租户相关API
  service.tenants = {
    list: function () {
      return service.get("/tenants");
    },
  };

  // 统计相关API
  service.stats = {
    dashboard: function () {
      return service.get("/stats/dashboard");
    },
  };

  // 部门相关API
  service.departments = {
    list: function (params = {}) {
      const queryString = Object.keys(params)
        .filter((key) => params[key] !== undefined && params[key] !== "")
        .map((key) => `${key}=${encodeURIComponent(params[key])}`)
        .join("&");

      const url = `/departments${queryString ? "?" + queryString : ""}`;
      return service.get(url);
    },

    create: function (departmentData) {
      return service.post("/departments", departmentData);
    },
  };

  // CI项目相关API
  service.ciItems = {
    list: function (params = {}) {
      const queryString = Object.keys(params)
        .filter((key) => params[key] !== undefined && params[key] !== "")
        .map((key) => `${key}=${encodeURIComponent(params[key])}`)
        .join("&");

      const url = `/ci-items${queryString ? "?" + queryString : ""}`;
      return service.get(url);
    },

    create: function (ciItemData) {
      return service.post("/ci-items", ciItemData);
    },
  };

  // 产品相关API
  service.products = {
    list: function (params = {}) {
      const queryString = Object.keys(params)
        .filter((key) => params[key] !== undefined && params[key] !== "")
        .map((key) => `${key}=${encodeURIComponent(params[key])}`)
        .join("&");

      const url = `/products${queryString ? "?" + queryString : ""}`;
      return service.get(url);
    },

    create: function (productData) {
      return service.post("/products", productData);
    },
  };

  // 产品模块相关API
  service.productModules = {
    list: function (params = {}) {
      const queryString = Object.keys(params)
        .filter((key) => params[key] !== undefined && params[key] !== "")
        .map((key) => `${key}=${encodeURIComponent(params[key])}`)
        .join("&");

      const url = `/product-modules${queryString ? "?" + queryString : ""}`;
      return service.get(url);
    },

    create: function (moduleData) {
      return service.post("/product-modules", moduleData);
    },
  };

  // 产品分类相关API
  service.productCategories = {
    list: function (params = {}) {
      const queryString = Object.keys(params)
        .filter((key) => params[key] !== undefined && params[key] !== "")
        .map((key) => `${key}=${encodeURIComponent(params[key])}`)
        .join("&");

      const url = `/product-categories${queryString ? "?" + queryString : ""}`;
      return service.get(url);
    },
  };

  return service;
};

function initHttpService() {
  const angular = window.angular;

  if (!angular) {
    console.error("Angular 未找到，无法初始化HTTP服务模块");
    return;
  }

  angular.module("app.services.http", []).service("HttpService", HttpService);
}

// Listen for vendor libs loaded event
window.addEventListener("vendorLibsLoaded", () => {
  initHttpService();
});

// If Angular already loaded, init directly
if (window.angular) {
  initHttpService();
}
